package com.hmdp.utils;

import cn.hutool.core.lang.UUID;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;

import java.sql.Time;
import java.util.Collections;
import java.util.concurrent.TimeUnit;

public class SimpleRedisLock implements ILock{
    private String name;
    private StringRedisTemplate redisTemplate;

    // 读入lua脚本文件
    private static final DefaultRedisScript<Long> UNLOCK_SCRIPT;
    static{
        UNLOCK_SCRIPT = new DefaultRedisScript<>();
        UNLOCK_SCRIPT.setLocation(new ClassPathResource("unlock.lua"));
        UNLOCK_SCRIPT.setResultType(Long.class);
    }

    public SimpleRedisLock(String name, StringRedisTemplate redisTemplate) {
        this.name = name;
        this.redisTemplate = redisTemplate;
    }
    private String prefix="lock:";
    private String prefix_id = UUID.randomUUID().toString(true)+"-";


    @Override
    public boolean tryLock(long timeout) {
        String id = prefix_id+Thread.currentThread().getId();

        // name是order:用户id
        Boolean success = redisTemplate.opsForValue().setIfAbsent(prefix + name, id , timeout, TimeUnit.SECONDS);
        return Boolean.TRUE.equals(success);
    }

    // 使用lua脚本使代码具有原子性
    @Override
    public void unlock() {
        // 一个lua脚本执行，具有原子性
        redisTemplate.execute(UNLOCK_SCRIPT, Collections.singletonList(prefix + name),prefix_id+Thread.currentThread().getId());
    }

//    @Override
//    public void unlock() {
//        // 避免误删锁
//        String lockid = prefix_id+Thread.currentThread().getId();
//
//        String id = redisTemplate.opsForValue().get(prefix + name);
//        if(lockid.equals(id)){
//            redisTemplate.delete(prefix + name);
//        }
//    }
}
